﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace collabr8
{
    // This class handles clipboard connections; there will be as many instances of it as there will be connected users
    class ClipConnection //: Connection
    {
        TcpClient tcpClient;
        // The thread that will send information to the client
        private Thread thrSender;
        private BinaryFormatter formatter;
        private Server server;
        private bool Connected;

        private Clip received;

        // The constructor of the class takes in a TCP connection
        public ClipConnection(TcpClient tcpCon) //: base(tcpCon)
        {
            tcpClient = tcpCon;
            server = Server.Instance;
            this.formatter = new BinaryFormatter();
            // The thread that accepts the client and awaits messages
            thrSender = new Thread(ReceiveClips);
            thrSender.IsBackground = true;
            // The thread calls the AcceptClient() method
            thrSender.Start();
        }

        public void CloseConnection()
        {
            // Close the currently open objects
            this.Connected = false;
            tcpClient.Close();
        }

        // Occures when a new client is accepted
        private void ReceiveClips()
        {
            this.Connected = true;
            try
            {
                // Keep waiting for a message from the user
                while (Connected)
                {
                    if (this.received != null)
                        this.received.Dispose();
                    this.received = (Clip)this.formatter.Deserialize(tcpClient.GetStream());
                    // TODO: Handle control messages
                    this.received.SaveFile("clips");
                    server.SendClip(this.received);
                }
            }
            catch
            {
                // If anything went wrong with this user, disconnect him
                server.RemoveClipUser(tcpClient);
                CloseConnection();
            }
        }
    }
}
